import 'package:flutter/material.dart';
import 'package:untitled/keep_alive_page.dart';
import 'package:video_player/video_player.dart';
import 'package:visibility_detector/visibility_detector.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: DefaultTabController(
          length: 3, // Number of tabs
          child: Column(
            children: <Widget>[
              TabBar(
                tabs: [
                  Tab(icon: Icon(Icons.home), text: 'Home'),
                  Tab(icon: Icon(Icons.search), text: 'Search'),
                  Tab(icon: Icon(Icons.person), text: 'Profile'),
                ],
              ),
              Expanded(
                  child: TabBarView(
                children: [
                  KeepAlivePage(
                    child: TestPage(page: 1,),
                  ),
                  KeepAlivePage(child: TestPage(page: 2,)),
                  KeepAlivePage(child: TestPage(page: 3)),
                ],
              ))
            ],
          )),
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("Page1 ");
    return Center(
      child: Text('Home Page'),
    );
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("Page2 ");
    return Center(
      child: Text('Search Page'),
    );
  }
}

class Page3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("Page3 ");
    return Center(
      child: Text('Profile Page'),
    );
  }
}

///页面保活方法
class TestPage extends StatefulWidget {
  const TestPage({super.key, required this.page});
  final int page;
  @override
  State<StatefulWidget> createState() {
    return _KeepAliveState();
  }
}

class _KeepAliveState extends State<TestPage> {
  List<VideoPlayerController> control = [];

  late VideoPlayerController _1controller;
  late VideoPlayerController _2controller;
  late VideoPlayerController _3controller;
  late VideoPlayerController _4controller;

  String flv="http://tv.drs.ganzitv.com:8100/channellive/gztv.flv?zsicd";
  String flv1="http://[2409:8087:1a01:df::70051/ottrrs.hl.chinamobile.com/PLTV/88888888/224/3221225734/index.m3u8";
  String flv2="http://[2409:8087:1a01:df::70051/ottrrs.hl.chinamobile.com/PLTV/88888888/224/3221225734/index.m3u8";
  String flv3="http://L2409:8087:1a01:df::70051/ottrrshl.chinamobile.com/PLTV/88888888/224/3221226008/index. m3u8";
  @override
  void initState() {
    super.initState();
    _1controller = VideoPlayerController.networkUrl(
      Uri.parse(
          flv),
      videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
    )..initialize().then((_) {
        setState(() {}); // 确保界面更新
        _1controller.play();
      });
    _2controller = VideoPlayerController.networkUrl(
      Uri.parse(
          flv),  videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
    )..initialize().then((_) {
        setState(() {}); // 确保界面更新
        _2controller.play();
      });
    _3controller = VideoPlayerController.networkUrl(
      Uri.parse(
          flv), videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
    )..initialize().then((_) {
        setState(() {}); // 确保界面更新
        _3controller.play();
      });
    _4controller = VideoPlayerController.networkUrl(
      Uri.parse(

          flv), videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
    )..initialize().then((_) {
        setState(() {}); // 确保界面更新
        _4controller.play();
      });
    control.add(_1controller);
    control.add(_2controller);
    control.add(_3controller);
    control.add(_4controller);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
            child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: VisibilityDetector(
                key: Key('${widget.page} 1'),
                onVisibilityChanged: (visibilityInfo) {
                  if (visibilityInfo.visibleFraction > 0.5) {
                    print("xxxx  vis ${widget.page}");
                    // _1controller.initialize();
                    _1controller.seekTo(_1controller.value.duration);
                    _1controller.play();
                  } else {
                    print("xxxx  gone ${widget.page}");
                    _1controller.pause();
                  }
                },
                child: VideoPlayer(_1controller),
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(child: VisibilityDetector(
              key: Key('${widget.page} 2'),
              onVisibilityChanged: (visibilityInfo) {
                if (visibilityInfo.visibleFraction > 0.5) {
                  // _2controller.initialize();
                  _2controller.seekTo(_1controller.value.duration);
                  _2controller.play();
                } else {
                  _2controller.pause();
                }
              },
              child: VideoPlayer(_2controller),
            ))
          ],
        )),
        SizedBox(
          height: 10,
        ),
        Expanded(
            child: Row(
          children: [
            Expanded(
              child: VisibilityDetector(
                key: Key('${widget.page} 3'),
                onVisibilityChanged: (visibilityInfo) {
                  if (visibilityInfo.visibleFraction > 0.5) {
                    // _3controller.initialize();
                    _3controller.seekTo(_1controller.value.duration);
                    _3controller.play();
                  } else {
                    _3controller.pause();
                  }
                },
                child: VideoPlayer(_3controller),
              ),
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(child: VisibilityDetector(
              key: Key('${widget.page} 4'),
              onVisibilityChanged: (visibilityInfo) {
                if (visibilityInfo.visibleFraction > 0.5) {
                  // _4controller.initialize();
                  _4controller.seekTo(_1controller.value.duration);
                  _4controller.play();
                } else {
                  _4controller.pause();
                }
              },
              child: VideoPlayer(_4controller),
            ))
          ],
        ))
      ],
    );
  }
}
